//
//  CQTemplateContainerView.m
//  TSDemo_ImageFilter
//
//  Created by qian on 2014/5/8.
//  Copyright (c) 2014年 dvlproad. All rights reserved.
//

#import "CQTemplateContainerView.h"

//#import "CQTemplateView.h"
#import "CQTemplateCell.h"

#import "CQTemplateRectHelper.h"
#import "BLTemplateRectHelper.h"

@interface CQTemplateContainerView () {
    
}
@property (nullable, nonatomic, copy, readonly) CAShapeLayer *(^ _Nullable realPointBorderLayerCreateBlock)(void);    /**< 真正的模板模型信息的边框layer创建(此属性为nil时候表示不设置边框)(创建layer时候不用提供path和frame,内部会自动补充) */
@property (nullable, nonatomic, copy, readonly) CAShapeLayer *(^ _Nullable selfBorderLayerCreateBlock)(UIRectCorner rectCorner);    /**< 本视图的边框layer创建方法(创建layer时候不用提供path和frame,内部会自动补充) */

@property (nonatomic, strong) NSMutableArray *anewDataModels;
@property (nonatomic, assign) NSInteger anewStyleIndex;   /**< 当前选择的模板index（从1开始) */
@property (nonatomic, assign, readonly) BOOL renderFrameOK; /**< 是否已经绘制过，防止卡片形式的模板列表里左右滑动的时候，会一直重绘 */

@end

@implementation CQTemplateContainerView

#pragma mark - Init
/*
 *  初始化
 *
 *  @param frame                frame
 *  @param initAnimate          布局结束后显示的缩放演示动画类型
 *
 *  @return 一整个完整的模板(里面包含小模板块)
 */
- (instancetype)initWithFrame:(CGRect)frame initAnimate:(CQTemplateInitAnimate)initAnimate {
    self = [super initWithFrame:frame templateCreateBlock:^CJTemplateBaseView *(NSInteger templateIndex) {
//        CQTemplateView *view = [[CQTemplateView alloc] initWithFrame:CGRectZero];
        BOOL showDemoAnimate = NO;
        if (initAnimate == CQTemplateInitAnimateAll) {
            showDemoAnimate = YES;
        } else if (initAnimate == CQTemplateInitAnimateFirst) {
            showDemoAnimate = templateIndex == 0;
        } else {
            showDemoAnimate = NO;
        }
        CQTemplateCell *view = [[CQTemplateCell alloc] initWithShowDemoAnimate:showDemoAnimate];
        // 友情提示：cell 背景色为透明，模板的背景色放在cell的容器中 CJTemplateContainerBaseView 的继承类里设置
        return view;
        
    } templateDataConfigBlock:^(CJTemplateBaseView *bTemplateView, id bDataModel, CJTemplateDataConfigTime time, NSInteger templateIndex) {
//        [(CQTemplateView *)bTemplateView setImageViewData:bDataModel];
        
        CQTemplateCell *templateCell = (CQTemplateCell *)bTemplateView;
        [templateCell updateImageByDataModel:bDataModel];
        
        
//        if (templateIndex == 0) {
//            CGRect templateCellFrame = templateCell.realTemplateModel.realSubFrame;
//            CGRect templateCellBounds = CGRectMake(0, 0, CGRectGetWidth(templateCellFrame), CGRectGetHeight(templateCellFrame));
//    //        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:templateCellBounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:(CGSizeMake(40, 40))];
//            UIBezierPath *path = templateCell.realTemplateModel.realTemplatePointPath;
//            CAShapeLayer *realPointBorderLayer = [CAShapeLayer layer];
//            realPointBorderLayer.path = [path CGPath];
//            realPointBorderLayer.fillColor = [[UIColor clearColor] CGColor]; // 必须透明
//            realPointBorderLayer.frame = templateCellBounds;
//            [realPointBorderLayer setLineWidth:10];
//            [realPointBorderLayer setStrokeColor:[UIColor redColor].CGColor];
//            [templateCell.imageView.layer addSublayer:realPointBorderLayer];
//        }
        
//        if (time == CJTemplateDataConfigTimeCreate) {
//            ((CQTemplateView *)bTemplateView).tapDelegate = self;
//        }
        
    } allowExchange:NO exchangeCompleteBlock:^{
        [self bringSubviewToFront:self.boardImageView];
    }];
    
    if (self) {
        self.backgroundColor = [UIColor whiteColor]; // 模板的背景色(模板cell是透明的)
        
        _boardImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        [_boardImageView setBackgroundColor:[UIColor clearColor]];
        [self addSubview:_boardImageView];
    }
    return self;
}

#pragma mark - layoutSubviews
- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self __checkAndResetFrame_ifNeedWithFroce:NO];
}


- (void)tapWithEditView:(CJTemplateBaseView *)sender
{
    if (_delegateMove && [_delegateMove respondsToSelector:@selector(movedEditView)]) {
        [_delegateMove movedEditView];
    }
}

#pragma mark - Setup
/*
 *  设置创建各种边框layer的方法(创建layer时候都不用提供path和frame,内部都会自动补充)
 *
 *  @param realPointBorderLayerCreateBlock  真正的模板模型信息的边框layer创建(此属性为nil时候表示不设置边框)
 *  @param selfBorderLayerCreateBlock       本视图的边框layer创建方法
 */
- (void)setupRealPointBorderLayerCreateBlock:(CAShapeLayer *(^ _Nullable)(void))realPointBorderLayerCreateBlock
                  selfBorderLayerCreateBlock:(CAShapeLayer *(^ _Nullable )(UIRectCorner rectCorner))selfBorderLayerCreateBlock
{
    _realPointBorderLayerCreateBlock = realPointBorderLayerCreateBlock;
    _selfBorderLayerCreateBlock = selfBorderLayerCreateBlock;
}

#pragma mark - Update
/*
 *  更新样式和数据
 *
 *  @param dataModels       模板中的模块个数dataModels.count、模板中的模块数据dataModel
 *  @param styleIndex       对应子框个数下的样式类型
 */
- (void)updateImagesByDataModels:(NSArray *)dataModels styleIndex:(NSInteger)styleIndex {
    self.anewStyleIndex = styleIndex;
    self.anewDataModels = [NSMutableArray arrayWithArray:dataModels];
    
    [self __updateTemplateWithSubViewCount:dataModels.count styleIndex:styleIndex];

    [self reloadTemplateCellWithDataModels:self.anewDataModels];
}


/*
 *  模板快个数不变的情况下的模板样式更新
 *
 *  @param styleIndex   对应子框个数下的样式类型
 */
- (void)updateStyleIndex:(NSInteger)styleIndex {
    [self __updateTemplateWithSubViewCount:self.cellCount styleIndex:styleIndex];
    
    [self bringSubviewToFront:self.boardImageView]; // 拼图边框移到最前
}

/*
 *  更新样式(注意：此更新方法必须等到布局结束，因为需要根据self.frame来布局模板)
 *
 *  @param subViewCount     样式的子框个数
 *  @param styleIndex       对应子框个数下的样式类型
 */
- (void)__updateTemplateWithSubViewCount:(NSInteger)subViewCount styleIndex:(NSInteger)styleIndex {
    CJTemplateModel *realTemplateModel = [BLTemplateRectHelper templateModelWithSubViewCount:subViewCount styleIndex:styleIndex];
    self.realTemplateModel = realTemplateModel;
    
//    if (self.cellCount == subViewCount && self.styleIndex == styleIndex) {
//        NSLog(@"友情提示：模板块个数%zd和该模板块个数下的模板样式%zd都未改变，不用重新设置模板块的各frame和各path", subViewCount, styleIndex);
//        return;
//    }
    
    [self __checkAndResetFrame_ifNeedWithFroce:NO];
    
    
    // 存在其他视图时候的处理
    [self bringSubviewToFront:self.boardImageView];
}

- (void)__checkAndResetFrame_ifNeedWithFroce:(BOOL)force {
    if (CGRectEqualToRect(self.frame, CGRectZero) == NO) {  // 视图已经布局好，可以获取模板在真正坐标系下的信息
        // 是否已经绘制过，防止卡片形式的模板列表里左右滑动的时候，会一直重绘
        if (self.renderFrameOK == NO && self.realTemplateModel != nil) {    // 模板dictionary已创建，视图frame等改变，则跟随改变
            // (注意：此更新方法必须等到布局结束，因为需要根据self.frame来布局模板)
            [BLTemplateRectHelper improveTemplateModel:self.realTemplateModel withRealSuperFrame:self.frame];
            
            [super improveTemplateWithRealTemplateModels:self.realTemplateModel.realTemplateModels realPointBorderLayerCreateBlock:self.realPointBorderLayerCreateBlock];
            _renderFrameOK = YES;
        }
    }
}

#pragma mark - Event
/*
 *  显示自己画的边框线段
 *
 *  @param rectCorner       rectCorner
 */
- (void)showPathForRectCorner:(UIRectCorner)rectCorner {
    [self showPathForRectCorner:rectCorner cornerRadius:self.layer.cornerRadius];
}

/*
 *  显示自己画的边框线段
 *
 *  @param rectCorner       rectCorner
 *  @param cornerRadius     cornerRadius
 */
- (void)showPathForRectCorner:(UIRectCorner)rectCorner cornerRadius:(CGFloat)cornerRadius {
    if (self.selfBorderLayerCreateBlock == nil) {
        NSLog(@"提示：未设置边框layer的创建方法，无法显示边框，请在调用此方法前，提前定义该selfBorderLayerCreateBlock");
        return;
    }
    
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat height = CGRectGetHeight(self.frame);
    CGFloat controlPointAdjust = 5;
    
    if (rectCorner && UIRectCornerTopLeft) {
        if (self.borderLayerTopLeft == nil) {
            self.borderLayerTopLeft = self.selfBorderLayerCreateBlock(rectCorner);
            [self.layer addSublayer:self.borderLayerTopLeft];
        }
        
//        CGRect borderRect = CGRectMake(0, 0, 80, 80);
//        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:borderRect byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:(CGSizeMake(40, 40))];
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint: CGPointMake(0, cornerRadius)];
        [bezierPath addQuadCurveToPoint:CGPointMake(cornerRadius, 0)
                           controlPoint:CGPointMake(0+controlPointAdjust, 0+controlPointAdjust)];
    //    [bezierPath addLineToPoint: CGPointMake(self.view.frame.size.width, showView.frame.size.height)];
    //    [bezierPath addLineToPoint: CGPointMake(0, showView.frame.size.height)];
        
        self.borderLayerTopLeft.path = bezierPath.CGPath;
    }
    
    if (rectCorner && UIRectCornerTopRight) {
        if (self.borderLayerTopRight == nil) {
            self.borderLayerTopRight = self.selfBorderLayerCreateBlock(rectCorner);
            [self.layer addSublayer:self.borderLayerTopRight];
        }
        
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint: CGPointMake(width-cornerRadius, 0)];
        [bezierPath addQuadCurveToPoint:CGPointMake(width, cornerRadius)
                           controlPoint:CGPointMake(width-controlPointAdjust, 0+controlPointAdjust)];
 
        self.borderLayerTopRight.path = bezierPath.CGPath;
    }
    
    if (rectCorner && UIRectCornerBottomLeft) {
        if (self.borderLayerBottomLeft == nil) {
            self.borderLayerBottomLeft = self.selfBorderLayerCreateBlock(rectCorner);
            [self.layer addSublayer:self.borderLayerBottomLeft];
        }
        
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint: CGPointMake(0, height-cornerRadius)];
        [bezierPath addQuadCurveToPoint:CGPointMake(cornerRadius, height)
                           controlPoint:CGPointMake(0+controlPointAdjust, height-controlPointAdjust)];
 
        self.borderLayerBottomLeft.path = bezierPath.CGPath;
    }
    
    if (rectCorner && UIRectCornerBottomRight) {
        if (self.borderLayerBottomRight == nil) {
            self.borderLayerBottomRight = self.selfBorderLayerCreateBlock(rectCorner);
            [self.layer addSublayer:self.borderLayerBottomRight];
        }
        
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint: CGPointMake(width-cornerRadius, height)];
        [bezierPath addQuadCurveToPoint:CGPointMake(width, height-cornerRadius)
                           controlPoint:CGPointMake(width-controlPointAdjust, height-controlPointAdjust)];
 
        self.borderLayerBottomRight.path = bezierPath.CGPath;
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
